package com.flying.tradingservice.service;

import com.flying.stockquotes.model.Quote;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Component
public class QuoteClient {
    private WebClient webClient;

    public QuoteClient(WebClient.Builder builder) {
        this.webClient = builder.build();
    }

    public Flux<Quote> quotesFeed() {
        return webClient.get().uri("http://localhost:18081/quotes")
                .accept(MediaType.APPLICATION_STREAM_JSON)
                .retrieve()
                .bodyToFlux(Quote.class);
    }

    public Mono<Quote> getLatestQuote(String ticker) {
        return quotesFeed()
                .filter(quote -> quote.getTicker().equalsIgnoreCase(ticker))
                .next()
                .timeout(Duration.ofSeconds(15), Mono.just(new Quote(ticker)));
    }
}
